package com.cool.cloud.controller;

import com.cool.cloud.entity.*;
import com.cool.cloud.utils.*;
import org.slf4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

/**
 * @ClassName: FileStoreController
 * @Description: 文件仓库控制器
 * @author: laijunju
 * @date 2020/2/6 16:04
 * @Version: 1.0
 **/
@Controller
public class FileStoreController extends BaseController {
    private Logger logger = LogUtils.getInstance(FileStoreController.class);

    /**
     * @return void
     * @Description 上传临时文件
     * @Author laijunju
     * @Date 23:14 2020/3/9
     * @Param [files]
     **/
    @PostMapping("/uploadTempFile")
    public String uploadTempFile(@RequestParam("file") MultipartFile file, String url) {
        session.setAttribute("imgPath", "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2654852821,3851565636&fm=26&gp=0.jpg");
        String name = file.getOriginalFilename().replaceAll(" ", "");
        if (!checkTarget(name)) {
            logger.error("临时文件上传失败!文件名不符合规范...");
            session.setAttribute("msg", "上传失败!文件名不符合规范");
            return "redirect:/temp-file";
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());
        String path = "temp/" + dateStr + "/" + UUID.randomUUID();
        try {
            if (FtpUtil.uploadFile("/" + path, name, file.getInputStream())) {
                //上传成功
                logger.info("临时文件上传成功!" + name);
                String size = String.valueOf(file.getSize());
                TempFile tempFile = TempFile.builder().fileName(name).filePath(path).size(size).uploadTime(new Date()).build();
                if (tempFileService.insert(tempFile)) {
                    try {
                        String id = UUID.randomUUID().toString();
                        String p = request.getSession().getServletContext().getRealPath("/user_img/");
                        url = url + "/share?code=" + id + "&f=" + tempFile.getFileId() + "&flag=2&p=" + size;
                        File targetFile = new File(p, "");
                        if (!targetFile.exists()) {
                            targetFile.mkdirs();
                        }
                        File f = new File(p, id + ".jpg");
                        if (!f.exists()) {
                            //文件不存在,开始生成二维码并保存文件
                            OutputStream os = new FileOutputStream(f);
                            QRCodeUtil.encode(url, "/static/img/CoolCloudLogo.png", os, true);
                            os.close();
                        }
                        //异步删除临时文件
                        tempFileService.deleteById(tempFile.getFileId());
                        session.setAttribute("imgPath", "user_img/" + id + ".jpg");
                        session.setAttribute("url", url);
                        session.setAttribute("msg", "上传成功，扫码/访问链接 即可下载！");
                        return "redirect:/temp-file";
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    logger.info("临时文件数据库写入失败!" + name);
                    session.setAttribute("url", "error");
                    session.setAttribute("msg", "服务器出错了，临时文件上传失败!");
                }
            } else {
                //上传失败
                logger.info("临时文件上传失败!" + name);
                session.setAttribute("url", "error");
                session.setAttribute("msg", "服务器出错了，上传失败!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:/temp-file";
    }

    /**
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @Description 网盘的文件上传
     * @Author laijunju
     * @Date 23:10 2020/2/10
     * @Param [files]
     **/
    @PostMapping("/uploadFile")
    @ResponseBody
    public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile files) {
        Map<String, Object> map = new HashMap<>();
        if (fileStoreService.getFileStoreByUserId(loginUser.getUserId()).getPermission() != 0) {
            logger.error("用户没有上传文件的权限!上传失败...");
            map.put("code", 499);
            return map;
        }
        FileStore store = fileStoreService.getFileStoreByUserId(loginUser.getUserId());
        Integer folderId = Integer.valueOf(request.getHeader("id"));
        String name = files.getOriginalFilename().replaceAll(" ", "");
        //获取当前目录下的所有文件，用来判断是否已经存在
        List<MyFile> myFiles = null;
        if (folderId == 0) {
            //当前目录为根目录
            myFiles = myFileService.getRootFilesByFileStoreId(loginUser.getFileStoreId());
        } else {
            //当前目录为其他目录
            myFiles = myFileService.getFilesByParentFolderId(folderId);
        }
        for (int i = 0; i < myFiles.size(); i++) {
            if ((myFiles.get(i).getMyFileName() + myFiles.get(i).getPostfix()).equals(name)) {
                logger.error("当前文件已存在!上传失败...");
                map.put("code", 501);
                return map;
            }
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());
        String path = loginUser.getUserId() + "/" + dateStr + "/" + folderId;
        if (!checkTarget(name)) {
            logger.error("上传失败!文件名不符合规范...");
            map.put("code", 502);
            return map;
        }
        Integer sizeInt = Math.toIntExact(files.getSize() / 1024);
        //是否仓库放不下该文件
        if (store.getCurrentSize() + sizeInt > store.getMaxSize()) {
            logger.error("上传失败!仓库已满。");
            map.put("code", 503);
            return map;
        }
        //处理文件大小
        String size = String.valueOf(files.getSize() / 1024.0);
        int indexDot = size.lastIndexOf(".");
        size = size.substring(0, indexDot);
        int index = name.lastIndexOf(".");
        String tempName = name;
        String postfix = "";
        int type = 4;
        if (index != -1) {
            tempName = name.substring(index);
            name = name.substring(0, index);
            //获得文件类型
            type = FileTypeUtil.getType(tempName.toLowerCase());
            postfix = tempName.toLowerCase();
        }
        try {
            //提交到FTP服务器
            boolean b = FtpUtil.uploadFile("/" + path, name + postfix, files.getInputStream());
            if (b) {
                //上传成功
                logger.info("文件上传成功!" + files.getOriginalFilename());
                //向数据库文件表写入数据
                myFileService.addFileByFileStoreId(
                        MyFile.builder()
                                .myFileName(name).fileStoreId(loginUser.getFileStoreId()).myFilePath(path)
                                .downloadTime(0).uploadTime(new Date()).parentFolderId(folderId).
                                size(Integer.valueOf(size)).type(type).postfix(postfix).build());
                //更新仓库表的当前大小
                fileStoreService.addSize(store.getFileStoreId(), Integer.valueOf(size));
                //更新当天该用户该类型文件数量
                LocalDate nowDate = LocalDate.now();
                int day = nowDate.getDayOfWeek().getValue();
                int count = fileWeekCountService.getTypeCount(day, loginUser.getUserId(), type);
                fileWeekCountService.update(day, loginUser.getUserId(), count + 1, type);
                try {
                    Thread.sleep(5000);
                    map.put("code", 200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                logger.error("文件上传失败!" + files.getOriginalFilename());
                map.put("code", 504);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * @return void
     * @Description 网盘的文件下载
     * @Author laijunju
     * @Date 23:13 2020/2/10
     * @Param [fId]
     * @Param [use]
     **/
    @GetMapping("/downloadFile")
    public String downloadFile(@RequestParam Integer fId, @RequestParam String use) {
        if (fileStoreService.getFileStoreByUserId(loginUser.getUserId()).getPermission() == 2 && !"show".equals(use)) {
            logger.error("用户没有下载文件的权限!下载失败...");
            return "redirect:/error401Page";
        }
        //获取文件信息
        MyFile myFile = myFileService.getFileByFileId(fId);
        String remotePath = myFile.getMyFilePath();
        String fileName = myFile.getMyFileName() + myFile.getPostfix();
        try {
            //去FTP上拉取
            OutputStream os = new BufferedOutputStream(response.getOutputStream());
            response.setCharacterEncoding("utf-8");
            // 设置返回类型
            response.setContentType("multipart/form-data");
            // 文件名转码一下，不然会出现中文乱码
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
            boolean flag = FtpUtil.downloadFile("/" + remotePath, fileName, os);
            if (flag) {
                if (!"show".equals(use)) {
                    myFileService.updateFile(
                            MyFile.builder().myFileId(myFile.getMyFileId()).downloadTime(myFile.getDownloadTime() + 1).build());
                }
                os.flush();
                os.close();
                logger.info("文件下载成功!" + myFile);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }

    /**
     * @return void
     * @Description 移动文件
     * @Author laijunju
     * @Date 23:13 2021/5/19
     **/
    @RequestMapping("/moveFile")
    public String moveFile(Integer fileId, String page, int cur, String searchName, Integer floderId) {
        HashMap rs = new HashMap();
        //根据选中文件id、选中文件夹id、更新文件记录中的parentId为新的文件夹id
        if (myFileService.moveFile(fileId, floderId) > 0) {
            session.setAttribute("tipmsg", "移动成功！");
        } else {
            session.setAttribute("tipmsg", "移动失败！");
        }
        //页面显示
        return returnPage(page, cur, searchName, null, null);
    }

    /**
     * @return void
     * @Description 获取可选目录
     * @Author laijunju
     * @Date 23:13 2021/5/19
     **/
    @ResponseBody
    @RequestMapping("/FileFloders")
    public List<FileFolder> getFolders() {
        return fileFolderService.getRootFoldersByFileStoreId(loginUser.getFileStoreId());
    }

    /**
     * @return java.lang.String
     * @Description 删除文件
     * @Author laijunju
     * @Date 23:14 2020/2/10
     * @Param [fId, folder]
     **/
    @GetMapping("/deleteFile")
    public String deleteFile(Integer fileId, String page, int cur, String searchName, String fId, String fName) {
        Integer fID = (fId == "" || fId == null) ? null : Integer.valueOf(fId);
        String fNAME = (fName == "" || fName == null) ? null : fName;
        //获得文件信息
        MyFile myFile = myFileService.getFileByFileId(fileId);
        String remotePath = myFile.getMyFilePath();
        String fileName = myFile.getMyFileName() + myFile.getPostfix();
        //从FTP文件服务器上删除文件
        try {
            FtpUtil.deleteFile("/" + remotePath, fileName);
        } catch (IOException e) {
            session.setAttribute("tipmsg", "删除文件失败!检查网络环境");
            logger.info("删除文件失败!文件：" + myFile + "报错：" + e.getMessage());
            return returnPage(page, cur, searchName, fID, fNAME);
        }
        //删除成功,返回空间
        fileStoreService.subSize(myFile.getFileStoreId(), Integer.valueOf(myFile.getSize()));
        //删除文件表对应的数据
        myFileService.deleteByFileId(fileId);
        //删除分享记录(有就删，没有什么也删不了)
        shareFileService.deleteByFileId(fileId);
        //更新当日该用户该类型文件数量统计信息
        LocalDate nowDate = LocalDate.now();
        int day = nowDate.getDayOfWeek().getValue();
        int count = fileWeekCountService.getTypeCount(day, loginUser.getUserId(), myFile.getType());
        fileWeekCountService.update(day, loginUser.getUserId(), Math.max((count - 1), 0), myFile.getType());


        session.setAttribute("tipmsg", "删除成功！");
        logger.info("删除文件成功!" + myFile);
        return returnPage(page, cur, searchName, fID, fNAME);
    }

    /**
     * @return java.lang.String
     * @Description 删除文件夹并清空文件
     * @Author laijunju
     * @Date 15:22 2020/2/12
     * @Param [fId]
     **/
    @GetMapping("/deleteFolder")
    public String deleteFolder(int fId, int cur) {
        FileFolder folder = fileFolderService.getFileFolderByFileFolderId(fId);
        //强制删除
        deleteFolderF(folder);
        return folder.getParentFolderId() == 0 ? "redirect:/file-all?cur=" + cur : "redirect:/file-all?fId=" + folder.getParentFolderId() + "&cur=" + cur;
    }

    /**
     * @return void
     * @Description 迭代删除文件夹里面的所有文件和子文件夹
     * @Author laijunju
     * @Date 9:17 2020/2/29
     * @Param [folder]
     **/
    public void deleteFolderF(FileFolder folder) {
        //获得当前文件夹下的所有子文件夹
        List<FileFolder> folders = fileFolderService.getFileFolderByParentFolderId(folder.getFileFolderId());
        //删除当前文件夹的所有的文件
        List<MyFile> files = myFileService.getFilesByParentFolderId(folder.getFileFolderId());
        LocalDate nowDate = LocalDate.now();
        int day = nowDate.getDayOfWeek().getValue();
        if (files.size() != 0) {
            for (int i = 0; i < files.size(); i++) {
                Integer fileId = files.get(i).getMyFileId();
                Integer type = files.get(i).getType();
                boolean optionrs = false;
                try {
                    optionrs = FtpUtil.deleteFile("/" + files.get(i).getMyFilePath(), files.get(i).getMyFileName() + files.get(i).getPostfix());
                } catch (IOException e) {
                    System.out.println("网络连接失败");
                }
                if (optionrs) {
                    myFileService.deleteByFileId(fileId);
                    fileStoreService.subSize(folder.getFileStoreId(), Integer.valueOf(files.get(i).getSize()));
                    //更新该用户当日该类型数量
                    int count = fileWeekCountService.getTypeCount(day, loginUser.getUserId(), type);
                    fileWeekCountService.update(day, loginUser.getUserId(), Math.max((count - 1), 0), type);
                }
            }
        }
        if (folders.size() != 0) {
            for (int i = 0; i < folders.size(); i++) {
                deleteFolderF(folders.get(i));
            }
        }
        fileFolderService.deleteFileFolderById(folder.getFileFolderId());
    }

    /**
     * @return java.lang.String
     * @Description 添加文件夹
     * @Author laijunju
     * @Date 23:16 2020/2/10
     * @Param [folder, map]
     **/
    @PostMapping("/addFolder")
    public String addFolder(FileFolder folder, Map<String, Object> map, int cur) {
        //设置文件夹信息
        folder.setFileStoreId(loginUser.getFileStoreId());
        folder.setTime(new Date());
        //获得当前目录下的所有文件夹,检查当前文件夹是否已经存在
        List<FileFolder> fileFolders = null;
        if (folder.getParentFolderId() == 0) {
            //向用户根目录添加文件夹
            fileFolders = fileFolderService.getRootFoldersByFileStoreId(loginUser.getFileStoreId());
        } else {
            //向用户的其他目录添加文件夹
            fileFolders = fileFolderService.getFileFolderByParentFolderId(folder.getParentFolderId());
        }
        for (int i = 0; i < fileFolders.size(); i++) {
            FileFolder fileFolder = fileFolders.get(i);
            if (fileFolder.getFileFolderName().equals(folder.getFileFolderName())) {
                logger.info("添加文件夹失败!文件夹已存在...");
                return "redirect:/file-all?error=1&fId=" + folder.getParentFolderId() + "&cur=" + cur;
            }
        }
        //向数据库写入数据
        Integer integer = fileFolderService.addFileFolder(folder);
        logger.info("添加文件夹成功!" + folder);
        return "redirect:/file-all?fId=" + folder.getParentFolderId() + "&cur=" + cur;
    }

    /**
     * @return java.lang.String
     * @Description 重命名文件夹
     * @Author laijunju
     * @Date 23:18 2020/2/10
     * @Param [folder, map]
     **/
    @PostMapping("/updateFolder")
    public String updateFolder(FileFolder folder, Map<String, Object> map, int cur) {
        //获得文件夹的数据库信息
        FileFolder fileFolder = fileFolderService.getFileFolderByFileFolderId(folder.getFileFolderId());
        fileFolder.setFileFolderName(folder.getFileFolderName());
        //获得当前目录下的所有文件夹,用于检查文件夹是否已经存在
        List<FileFolder> fileFolders = fileFolderService.getFileFolderByParentFolderId(fileFolder.getParentFolderId());
        for (int i = 0; i < fileFolders.size(); i++) {
            FileFolder folder1 = fileFolders.get(i);
            if (folder1.getFileFolderName().equals(folder.getFileFolderName()) && folder1.getFileFolderId() != folder.getFileFolderId()) {
                logger.info("重命名文件夹失败!文件夹已存在...");
                return "redirect:/file-all?error=2&fId=" + fileFolder.getParentFolderId() + "&cur=" + cur;
            }
        }
        //向数据库写入数据
        Integer integer = fileFolderService.updateFileFolderById(fileFolder);
        logger.info("重命名文件夹成功!" + folder);
        return "redirect:/file-all?fId=" + fileFolder.getParentFolderId() + "&cur=" + cur;
    }

    /**
     * @return java.lang.String
     * @Description 重命名文件
     * @Author laijunju
     * @Date 12:47 2020/2/12
     * @Param [file, map]
     **/
    @PostMapping("/updateFileName")
    public String updateFileName(Integer myFileId, String myFileName, String page, int cur, String searchName, String fId, String fName) {
        MyFile myFile = myFileService.getFileByFileId(myFileId);
        Integer fID = (fId == "" || fId == null) ? null : Integer.valueOf(fId);
        String fNAME = (fName == "" || fName == null) ? null : fName;
        if (myFile != null) {
            String oldName = myFile.getMyFileName();
            String newName = myFileName;
            if (!oldName.equals(newName)) {
                try {
                    FtpUtil.reNameFile(myFile.getMyFilePath() + "/" + oldName + myFile.getPostfix(), myFile.getMyFilePath() + "/" + newName + myFile.getPostfix());
                } catch (IOException e) {
                    logger.info("修改文件名失败!文件：" + myFile + "，报错：" + e.getMessage());
                    session.setAttribute("tipmsg", "修改文件名失败!检查网络环境");
                    return returnPage(page, cur, searchName, fID, fNAME);
                }
                myFileService.updateFile(MyFile.builder().myFileId(myFile.getMyFileId()).myFileName(newName).build());
                logger.info("修改文件名成功!原文件名:" + oldName + "  新文件名:" + newName);
                session.setAttribute("tipmsg", "修改文件名成功!");
                return returnPage(page, cur, searchName, fID, fNAME);
            }
            session.setAttribute("tipmsg", "与原文件名相同，无需修改！");
            return returnPage(page, cur, searchName, fID, fNAME);
        }
        session.setAttribute("tipmsg", "文件名不能为空！");
        return returnPage(page, cur, searchName, fID, fNAME);
    }


    /**
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @Description 获得二维码
     * @Author laijunju
     * @Date 15:20 2020/2/12
     * @Param [id, url]
     **/
    @GetMapping("getQrCode")
    @ResponseBody
    public Map<String, Object> getQrCode(FileShare share) throws InterruptedException {
        Map<String, Object> map = new HashMap<>();
        String profixurl = share.getUrl().split("coolcloud")[0] + "coolcloud";
        map.put("imgPath", "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2654852821,3851565636&fm=26&gp=0.jpg");
        if (share.getFileId() != null) {
            MyFile file = myFileService.getFileByFileId(share.getFileId());
            if (file != null) {
                share.setUserid(loginUser.getUserId()).setCreateTime(new Date());
                if (share.getIsOpenDecrypt() == 1) {
                    share.setUnDecrypt(share.getDecrypt());
                    share.setDecrypt(MD5Utils.getSaltMD5(share.getDecrypt()));
                }
                share.setSize(file.getSize().toString()).setFileName(file.getMyFileName() + file.getPostfix());
                FileShare fileshare = shareFileService.queryByFileId(share.getFileId());
                String url = UUID.randomUUID().toString();
                share.setUrl(url);
                if (share.getUnDecrypt() == null) {
                    share.setUnDecrypt("unset");
                }
                if (fileshare == null) {
                    shareFileService.insert(share);
                } else {
                    if (share.getEndDateType() == null) {
                        share.setEndDateType(0);
                    }
                    shareFileService.updateByFileId(share);
                }
                if (share.getIsOpenEnddate() == 1) {
                    shareFileService.deleteByCon(share);
                }
                try {
                    String path = request.getSession().getServletContext().getRealPath("/user_img/");
                    url = profixurl + "/share?code=" + url + "&f=" + share.getFileId() + "&flag=1&p=unknown";
                    File targetFile = new File(path, "");
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                    }
                    File f = new File(path, share.getFileId() + ".jpg");
                    if (!f.exists()) {
                        //文件不存在,开始生成二维码并保存文件
                        OutputStream os = new FileOutputStream(f);
                        QRCodeUtil.encode(url, "/static/img/CoolCloudLogo.png", os, true);
                        os.close();
                    }
                    map.put("imgPath", "user_img/" + share.getFileId() + ".jpg");
                    map.put("password", share.getUnDecrypt());
                    map.put("url", url);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return map;
    }

    /**
     * @return void
     * @Description 分享文件
     * @Author laijunju
     * @Date 14:23 2020/2/12
     * @Param [fId]
     **/
    @GetMapping("/share")
    public String shareFile(@RequestParam String code, @RequestParam String f, @RequestParam Integer flag, @RequestParam String p) {
        String fileNameTemp = "";
        String remotePath = "";
        String fileName = "";
        Integer times = 0;
        if (flag == null || f == null || code == null) {
            logger.info("下载分享文件失败，参数错误");
            return "redirect:/error400Page";
        }
        if (flag == 1) {
            //获取文件信息
            FileShare share = shareFileService.queryByUrl(code);
            if (share == null) {
                return "redirect:/error404Page";
            }
            MyFile myFile = myFileService.getFileByFileId(share.getFileId());
            if (myFile == null) {
                return "redirect:/error404Page";
            }
            //密码加密跳转密码输入界面
            if (share.getIsOpenDecrypt() == 1 && p.equals("unknown")) {
                request.setAttribute("code", code);
                request.setAttribute("f", f);
                request.setAttribute("flag", flag);
                request.setAttribute("filename", myFile.getMyFileName() + myFile.getPostfix());
                return "main/toWriteFilePsd";
            } else if ((share.getIsOpenDecrypt() == 1 && MD5Utils.getSaltverifyMD5(p, share.getDecrypt())) || share.getIsOpenDecrypt() == 0) {
                remotePath = myFile.getMyFilePath();
                fileName = myFile.getMyFileName() + myFile.getPostfix();
            } else if (share.getIsOpenDecrypt() == 1 && !MD5Utils.getSaltverifyMD5(p, share.getDecrypt())) {
                request.setAttribute("code", code);
                request.setAttribute("f", f);
                request.setAttribute("flag", flag);
                request.setAttribute("filename", myFile.getMyFileName() + myFile.getPostfix());
                request.setAttribute("tip", "密码错误！");
                return "main/toWriteFilePsd";
            }
        } else if (flag == 2) {
            TempFile tempFile = tempFileService.queryById(Integer.valueOf(f));
            if (tempFile == null) {
                return "redirect:/error404Page";
            }

            String pwd = tempFile.getSize();
            if (!pwd.equals(p)) {
                return "redirect:/error400Page";
            }
            remotePath = tempFile.getFilePath();
            fileName = tempFile.getFileName();
        } else {
            return "redirect:/error400Page";
        }
        fileNameTemp = fileName;
        try {
            //解决下载文件时 中文文件名乱码问题
            boolean isMSIE = isMSBrowser(request);
            if (isMSIE) {
                //IE浏览器的乱码问题解决
                fileNameTemp = URLEncoder.encode(fileNameTemp, "UTF-8");
            } else {
                //万能乱码问题解决
                fileNameTemp = new String(fileNameTemp.getBytes("UTF-8"), "ISO-8859-1");
            }
            //去FTP上拉取
            OutputStream os = new BufferedOutputStream(response.getOutputStream());
            response.setCharacterEncoding("utf-8");
            // 设置返回类型
            response.setContentType("multipart/form-data");
            // 文件名转码一下，不然会出现中文乱码
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileNameTemp);
            if (FtpUtil.downloadFile("/" + remotePath, fileName, os)) {
                myFileService.updateFile(
                        MyFile.builder().myFileId(Integer.valueOf(f)).downloadTime(times + 1).build());
                os.flush();
                os.close();
                logger.info("文件下载成功!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }

    /**
     * @return boolean
     * @Description 正则验证文件名是否合法 [汉字,字符,数字,下划线,英文句号,横线]
     * @Author laijunju
     * @Date 23:22 2020/2/10
     * @Param [target]
     **/
    public boolean checkTarget(String target) {
//        final String format = "[^\\u4E00-\\u9FA5\\uF900-\\uFA2D\\w-_.]";
//        Pattern pattern = Pattern.compile(format);
//        Matcher matcher = pattern.matcher(target);
//        return !matcher.find();
        return true;
    }

    /**
     * @return boolean
     * @Description 判断当前浏览器是否为ie
     * @Author laijunju
     * @Date 22:39 2020/3/5
     * @Param [request]
     **/
    public static boolean isMSBrowser(HttpServletRequest request) {
        String[] IEBrowserSignals = {"MSIE", "Trident", "Edge"};
        String userAgent = request.getHeader("User-Agent");
        for (String signal : IEBrowserSignals) {
            if (userAgent.contains(signal)) {
                return true;
            }
        }
        return false;
    }
}
